/*
描述：问题详情视图组件，展示问题内容、评论、点赞等功能
完成人：何艺珲
完成时间: 2025/04/26
*/


<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { ref, onMounted } from 'vue';
import axios, { AxiosError } from 'axios';
import { Calendar } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus'
import RecentQuestion from "@/components/HomeView/RecentQuestion.vue";
import HeaderComponent from "@/components/HomeView/HeaderComponent.vue";
const route = useRoute();
const router = useRouter();

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login');
};


const questionId = ref<number | null>(null);


const isLoggedIn = ref(false);
const userName = ref<string | null>(null);
const avatar = ref<string>('');

interface Question {
  id: number;
  title: string;
  content: string;
  img: string;
  createtime: string;
  updatetime?: string | null;
  user_id: number;
  likes: number;
  answercount?: number;
  username?: string;
  avatar?: string;
}


const question = ref<Question>({
  id: 0,
  title: '',
  content: '',
  img: '',
  createtime: '',
  updatetime: null,
  user_id: 0,
  likes: 0,
  answercount: 0,
  username: '',
  avatar: ''
});
//提问者信息
interface UserInfo{
  id: number;
  username: string;
  avatar: string;
}

const userInfo = ref<UserInfo>({
  id: 0,
  username: '',
  avatar: ''
});

// 点赞状态
const isLiked = ref<boolean>(false);
const likeLoading = ref<boolean>(false);

// 评论信息
interface Comment{
  id: number;
  content: string;
  createtime: string;
  like: number;
  user_id: number;
  question_id: number;
  user?: UserInfo;
}
const comments = ref<Comment[]>([
  {
    id: 0,
    content: '',
    createtime: '',
    like: 0,
    user_id: 0,
    question_id: 0

  }
]);

// 新评论内容
const newComment = ref<string>('');
// 提交评论时的加载状态
const submitting = ref<boolean>(false);
// 错误信息
const errorMessage = ref<string>('理性发言，友善讨论');


const formatDate = (dateString: string): string => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }).toUpperCase();
};


const fetchQuestion = async (): Promise<void> => {
  try {

    questionId.value = route.query.id ? Number(route.query.id) : null;

    if (!questionId.value) {
      console.warn('No question ID provided');
      return;
    }

    const response = await axios.post<{
      code: number;
      msg: string;
      data: Question[]
    }>(
        'http://localhost:8089/question/getQuestionList',
        {
          id: questionId.value,
          title: '',
          content: '',
          user_id: '',
        },
        {
          headers: {
            'Content-Type': 'application/json',
            Accept: '*/*',
          },
        }
    );

    if (response.data.code === 1 && response.data.data.length > 0) {
      question.value = response.data.data[0]; // Since only one question is returned


      const response1 = await axios.get(
          'http://localhost:8089/user/getUserInfo'
          , {
            headers: {
              'Content-Type': 'application/json',
              'Accept': '*/*'
            },
            params: {id:question.value.user_id}
          }
      );
      userInfo.value = response1.data.data;
      console.log(question.value)



    } else {
      console.warn('No question data returned or invalid response code');
    }
  } catch (error) {
    const axiosError = error as AxiosError;
    console.error('Error fetching question:', axiosError.message);
  }
};


const fetchCommentsInfo = async (): Promise<void> => {
  try {
    // Fetch comments
    const commentsResponse = await axios.get(
        'http://localhost:8089/question/getQuestionComment',
        {
          headers: {
            'Content-Type': 'application/json',
            'Accept': '*/*'
          },
          params: { id: questionId.value }
        }
    );

    const fetchedComments = commentsResponse.data.data;


    const commentsWithUsers = await Promise.all(
        fetchedComments.map(async (comment: Comment) => {
          try {
            const userResponse = await axios.get(
                'http://localhost:8089/user/getUserInfo',
                {
                  headers: {
                    'Content-Type': 'application/json',
                    'Accept': '*/*'
                  },
                  params: { id: comment.user_id }
                }
            );
            return {
              ...comment,
              user: userResponse.data.data
            };
          } catch (error) {
            const axiosError = error as AxiosError;
            console.error(`Error fetching user info for comment ${comment.id}:`, axiosError.message);
            return {
              ...comment,
              user: { id: comment.user_id, username: 'Unknown', avatar: '' }
            };
          }
        })
    );

    comments.value = commentsWithUsers;
  } catch (error) {
    const axiosError = error as AxiosError;
    console.error('Error fetching comments:', axiosError.message);
  }
};
// 提交评论
const submitComment = async (): Promise<void> => {
  // 检查用户是否登录
  if (!isLoggedIn.value) {
    errorMessage.value = '请先登录后再发表评论';
    return;
  }

  // 检查评论内容是否为空
  if (!newComment.value.trim()) {
    errorMessage.value = '评论内容不能为空';
    return;
  }

  try {
    submitting.value = true;
    errorMessage.value = '';

    // 获取当前用户ID
    const userId = localStorage.getItem('id');

    // 发送评论到服务器
    const response = await axios.post(
      'http://localhost:8089/comment/insertComment',
      {
        content: newComment.value,
        user_id: userId,
        question_id: questionId.value
      },
      {
        headers: {
          token:localStorage.getItem('token'),
          'Content-Type': 'application/json',
          'Accept': '*/*',
          'Authorization': localStorage.getItem('token') || ''
        }
      }
    );

    if (response.data && response.data.code === 1) {
      // 评论成功，清空输入框
      newComment.value = '';
      // 重新获取评论列表
      await fetchCommentsInfo();

      // 发送消息
      errorMessage.value = '正在发送中......';
      // 人为延迟5秒，保持加载状态
      await new Promise(resolve => setTimeout(resolve, 500));

      // 显示成功提示消息
      ElMessage({
        message: '评论发送成功！',
        type: 'success',
        duration: 3000
      });

      // 重置错误消息为初始友好提示
      errorMessage.value = '理性发言，友善讨论';
    } else {
      errorMessage.value = response.data.msg || '评论发送失败，请稍后再试';
      // 显示错误提示
      ElMessage({
        message: '评论发送失败，请稍后再试',
        type: 'error',
        duration: 3000
      });
    }
  } catch (error) {
    const axiosError = error as AxiosError;
    console.error('Error submitting comment:', axiosError.message);
    errorMessage.value = '评论发送失败，请稍后再试';
    // 显示错误提示
    ElMessage({
      message: '评论发送失败，请稍后再试',
      type: 'error',
      duration: 3000
    });
  } finally {
    submitting.value = false;
  }
};

// 获取点赞状态
const fetchLikeStatus = async (): Promise<void> => {
  if (!isLoggedIn.value || !questionId.value) return;

  try {
    const userId = localStorage.getItem('id');
    if (!userId) return;

    const response = await axios.post(
      'http://localhost:8089/like/getLikeStatus',
      {
        userId: Number(userId),
        targetType: 0, // 0代表问题点赞
        targetId: questionId.value
      },
      {
        headers: {
          token: localStorage.getItem('token') || '',
          'Content-Type': 'application/json',
          'Accept': '*/*'
        }
      }
    );

    // 根据API返回判断点赞状态
    // code为1表示已点赞，code为0表示未点赞
    isLiked.value = response.data.code === 1;
  } catch (error) {
    const axiosError = error as AxiosError;
    console.error('Error fetching like status:', axiosError.message);
  }
};

// 点赞/取消点赞
const toggleLike = async (): Promise<void> => {
  if (!isLoggedIn.value) {
    ElMessage({
      message: '请先登录后再点赞',
      type: 'warning',
      duration: 3000
    });
    return;
  }

  if (!questionId.value) return;

  try {
    likeLoading.value = true;
    const userId = localStorage.getItem('id');
    if (!userId) return;

    if (isLiked.value) {
      // 取消点赞
      await axios.request({
        method: 'DELETE',
        url: 'http://localhost:8089/like/deleteLikeRecord',
        headers: {
          token: localStorage.getItem('token') || '',
          'Content-Type': 'application/json',
          'Accept': '*/*'
        },
        data: {
          userId: Number(userId),
          targetType: 0, // 0代表问题点赞
          targetId: questionId.value
        }
      });

      // 更新UI
      isLiked.value = false;
      if (question.value.likes > 0) {
        question.value.likes -= 1;
      }

      ElMessage({
        message: '已取消点赞',
        type: 'warning',
        duration: 2000
      });
    } else {
      // 添加点赞
      await axios.post(
        'http://localhost:8089/like/addLikeRecord',
        {
          userId: Number(userId),
          targetType: 0, // 0代表问题点赞
          targetId: questionId.value
        },
        {
          headers: {
            token: localStorage.getItem('token') || '',
            'Content-Type': 'application/json',
            'Accept': '*/*'
          }
        }
      );

      // 更新UI
      isLiked.value = true;
      question.value.likes += 1;

      ElMessage({
        message: '点赞成功',
        type: 'success',
        duration: 2000
      });
    }
  } catch (error) {
    const axiosError = error as AxiosError;
    console.error('Error toggling like:', axiosError.message);

    ElMessage({
      message: '操作失败，请稍后再试',
      type: 'error',
      duration: 3000
    });
  } finally {
    likeLoading.value = false;
  }
};

// 标签信息
interface Tag {
  id: number;
  tagname: string;
  content: string;
}

const tags = ref<Tag[]>([]);

// 获取问题标签
const fetchQuestionTags = async (): Promise<void> => {
  try {
    if (!questionId.value) {
      console.warn('No question ID provided for fetching tags');
      return;
    }

    const response = await axios.get(
      'http://localhost:8089/question/getQuestionTag',
      {
        headers: {
          'Accept': '*/*',
        },
        params: { id: questionId.value }
      }
    );

    if (response.data && response.data.code === 1) {
      tags.value = response.data.data;
    } else {
      console.warn('No tags data returned or invalid response code');
    }
  } catch (error) {
    const axiosError = error as AxiosError;
    console.error('Error fetching question tags:', axiosError.message);
  }
};

// Initialize on component mount
onMounted(() => {
  isLoggedIn.value = !!localStorage.getItem('token');
  userName.value = localStorage.getItem('username');
  avatar.value = localStorage.getItem('avatar') || '';
  fetchQuestion();
  // fetchUserInfo();//获得问题作者信息
  fetchCommentsInfo();
  fetchLikeStatus(); // 获取点赞状态
  fetchQuestionTags(); // 获取问题标签
});
</script>

<template>
  <div class="common-layout">
    <el-container>
      <HeaderComponent />
      <el-container>
        <el-aside width="500px" style="height: 100vh">
        </el-aside>
        <el-main class="body">
          <!-- Image -->
          <div class="image-container">
            <img v-if="question.img" :src="question.img" alt="Question Image" class="question-image" />
          </div>

          <!-- Headline -->
          <h1 class="headline">{{ question.title }}</h1>

          <!-- Content -->
          <p class="content">{{ question.content }}</p>

          <!-- Tags (在文章下方) -->
          <div class="tags-container">
            <el-tag
              v-for="tag in tags"
              :key="tag.id"
              class="tag-item"
              type="info"
              effect="plain"
            >
              {{ tag.tagname }}
            </el-tag>
          </div>

          <!-- Likes -->
          <div class="likes-container">


            <div class="left-section">
              <img :src="userInfo.avatar" alt="Author Avatar" class="author-avatar" />
              <div class="author-info">
                <span class="author-username">{{ userInfo.username }}</span>
                <span class="author-label">Author</span>
              </div>
            </div>
            <div class="right-section">
              <el-icon><Calendar /></el-icon>
              <span class="date">{{ formatDate(question.createtime) }}</span>
              <el-button
                type="text"
                :loading="likeLoading"
                @click="toggleLike"
                class="like-button"
              >
                <el-icon :class="{ 'liked': isLiked }">
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
                  </svg>
                </el-icon>
                <span>{{ question.likes }} 点赞</span>
              </el-button>
            </div>
          </div>

          <!-- AddComment -->
          <div class="comment-container add-comment-container">
            <div v-if="isLoggedIn" class="comment-form">
              <el-input
                v-model="newComment"
                type="textarea"
                :rows="3"
                placeholder="写下你的评论..."
                resize="none"
                class="comment-textarea"
              />
              <div class="comment-form-footer">
                <span v-if="errorMessage" class="error-message">{{ errorMessage }}</span>
                <el-button
                  type="primary"
                  @click="submitComment"
                  :loading="submitting"
                  class="submit-button"
                >
                  发表评论
                </el-button>
              </div>
            </div>
            <div v-else class="login-prompt">
              <p>请<el-button type="text" @click="goToLogin" class="login-link">登录</el-button>后发表评论</p>
            </div>
          </div>



          <!-- Comments -->
          <div v-for="(comment, index) in [...comments].reverse()" :key="index" class="comment-container">
            <div class="comment-header">
              <div class="comment-author">
                <img v-if="comment.user" :src="comment.user.avatar" alt="Commenter Avatar" class="comment-avatar" />
                <span v-if="comment.user" class="comment-username">{{ comment.user.username }}</span>
              </div>
              <span class="comment-date">{{ formatDate(comment.createtime) }}</span>
            </div>
            <p class="comment-content">{{ comment.content }}</p>
          </div>
        </el-main>
        <el-aside width="500px">
          <div class="sidebar-menu-right">
            <RecentQuestion/>
          </div>
        </el-aside>
      </el-container>
    </el-container>
  </div>
</template>

<style scoped>

*{
  background-color: #F9FAFA;
}

/* 添加评论样式 */
.add-comment-container {
  margin-bottom: 30px;
}

.comment-form {
  display: flex;
  flex-direction: column;
  gap: 12px;
  background-color: #FFFFFF;
}

.comment-form-header {
  display: flex;
  align-items: center;
  gap: 10px;
  background-color: #FFFFFF;
}

.comment-textarea {
  background-color: #FFFFFF;
}

.comment-form-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  background-color: #FFFFFF;
}

.error-message {
  color: #8a8a8a;
  font-size: 14px;
  background-color: #FFFFFF;
  margin-right: auto;
}

.submit-button {
  background-color: #E7700D;
  border-color: #E7700D;
  width: 100px; /* 添加固定宽度 */
  min-width: 100px; /* 确保最小宽度 */
}

.submit-button:hover {
  background-color: #d86600;
  border-color: #d86600;
}

.error-message {
  color: #8a8a8a;
  font-size: 14px;
  background-color: #FFFFFF;
}

.login-prompt {
  text-align: center;
  padding: 20px;
  background-color: #FFFFFF;
}

.login-prompt p {
  background-color: #FFFFFF;
  margin: 0;
}

.login-link {
  color: #E7700D;
  font-weight: bold;
  background-color: #FFFFFF;
}


.body {
  height: 100%;
  padding: 84px 20px 20px 20px;
  background-color: #F9FAFA;
}

.date {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  color: #666;
  margin-bottom: 0;
  background-color: #F9FAFA;
}

.date .el-icon {
  background-color: #F9FAFA;
}

.headline {
  font-size: 36px;
  font-weight: bold;
  line-height: 1.2;
  margin-bottom: 10px;
  color: #000;
  background-color: #F9FAFA;
}

.subtitle {
  font-size: 16px;
  color: #555;
  margin-bottom: 20px;
  font-style: italic;
  background-color: #F9FAFA;
}

.image-container {
  width: 100%;
  max-width: 600px;
  margin: 0 auto 20px auto;
  background-color: #F9FAFA;
}

.question-image {
  width: 100%;
  height: auto;
  border-radius: 8px;
  object-fit: cover;
  background-color: #F9FAFA;
}

.content {
  font-size: 16px;
  line-height: 1.6;
  color: #333;
  background-color: #F9FAFA;
}



.logo{
  display: flex;
  align-items: center;
  width: 100px;
  height: 40px;
  background-color: white;
  cursor: pointer;
  margin-left: 10%;
}
.logo span{
  background-color: white;
  margin-left: 7px;
  font-size: 20px;
  color: #BCBBBB;

}



.right-button{
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
  background-color: white;
}


.sidebar-menu-right {
  position: fixed;  /* 元素脱离文档流，相对于浏览器窗口固定定位 */
  top: 84px;
}
/* Likes Container */
.likes-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #666;
  margin: 15px 0;
  background-color: #F9FAFA;
  padding: 8px 12px;
  border: 1px solid #D6D9DC;
  border-radius: 8px;
  width: 97%;
}
.left-section {
  display: flex;
  align-items: center;
  gap: 8px;
  background-color: #F9FAFA;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 8px;
  background-color: #F9FAFA;
}

.likes-container .el-icon {
  background-color: #F9FAFA;
  color: #E7700D;
}

.date {
  margin-right: 20px;
  background-color: #F9FAFA;
}
.author-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  background-color: #F9FAFA;
}

.author-info {
  display: flex;
  flex-direction: column;
  background-color: #F9FAFA;
}

.author-username {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  background-color: #F9FAFA;
}

.author-label {
  font-size: 12px;
  color: #666;
  background-color: #F9FAFA;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .likes-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .left-section, .right-section {
    width: 100%;
    justify-content: flex-start;
  }

  .right-section {
    justify-content: flex-end;
  }
}

@media (max-width: 480px) {
  .author-avatar {
    width: 32px;
    height: 32px;
  }

  .author-username {
    font-size: 14px;
  }

  .author-label {
    font-size: 10px;
  }

  .date {
    margin-right: 10px;
  }
}
/* Comment Container */
.comment-container {
  margin: 15px 0;
  padding: 15px;
  background-color: #FFFFFF;
  border: 1px solid #D6D9DC;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  background-color: #FFFFFF;
}

.comment-author {
  display: flex;
  align-items: center;
  gap: 10px;
  background-color: #FFFFFF;
}

.comment-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
  background-color: #F9FAFA;
}

.comment-username {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  background-color: #FFFFFF;
}

.comment-date {
  font-size: 12px;
  color: #666;
  background-color: #FFFFFF;
}

.comment-content {
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  margin: 0;
  background-color: #FFFFFF;
}
.like-button {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
  background-color: transparent;
  border: none;
  cursor: pointer;
  padding: 5px 10px;
  transition: all 0.3s ease;
  background-color: #F9FAFA;
}

.like-button:hover {
  color: #E7700D;
}

.like-button .el-icon {
  font-size: 18px;
  background-color: #F9FAFA;
  transition: all 0.3s ease;
}

.like-button .liked {
  color: #E7700D;
  fill: #E7700D;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .likes-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .left-section, .right-section {
    width: 100%;
    justify-content: flex-start;
  }

  .right-section {
    justify-content: flex-end;
  }
}

@media (max-width: 480px) {
  .author-avatar {
    width: 32px;
    height: 32px;
  }

  .author-username {
    font-size: 14px;
  }

  .author-label {
    font-size: 10px;
  }

  .date {
    margin-right: 10px;
  }
}
/* Comment Container */
.comment-container {
  margin: 15px 0;
  padding: 15px;
  background-color: #FFFFFF;
  border: 1px solid #D6D9DC;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  background-color: #FFFFFF;
}

.comment-author {
  display: flex;
  align-items: center;
  gap: 10px;
  background-color: #FFFFFF;
}

.comment-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
  background-color: #F9FAFA;
}

.comment-username {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  background-color: #FFFFFF;
}

.comment-date {
  font-size: 12px;
  color: #666;
  background-color: #FFFFFF;
}

.comment-content {
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  margin: 0;
  background-color: #FFFFFF;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 15px;
  margin-top:10px;
  margin-left: 10px;
  background-color: #F9FAFA;
}

.tag-item {
  background-color: #ffe8de;
  color: #E7700D;
  border-color: #eaddd2;
  font-size: 12px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
  border-radius: 4px;
}
</style>



